/* 
 * $Id$
 * CONFIDENTIAL AND PROPRIETARY. (c)  2007 Revolution Health Group LLC. All rights reserved. 
 * This source code may not be disclosed to others, used or reproduced without the written permission of Revolution Health Group.
 * 
 */
package org.javason.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class HttpServletRequestUtils {
	private static final Logger LOG = Logger.getLogger(HttpServletRequestUtils.class);
	public static final String VERSION = "$Rev$";

	private HttpServletRequestUtils() {}
	
	public static String getRequestContent(HttpServletRequest request) throws UnsupportedEncodingException, IOException {
		BufferedReader input = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
		
		StringBuilder inputString = new StringBuilder();
		String line = input.readLine();
		while (line != null) {
			inputString.append(line);
			line = input.readLine();
		}
		return inputString.toString();
	}
	
	public static List<String> splitPath(String pathInfo) {
		int chompTo = pathInfo.replaceFirst("\\?.*", "").lastIndexOf('/');
		
		if (chompTo < 0) {
			chompTo = 0;
		}
		
		String[] path = pathInfo.substring(chompTo).split("/|\\?|\\&");
		List<String> result = new LinkedList<String>(); 
		for (int i = 0; i < path.length; i++) {
			if (path[i].length() > 0) {
				result.add(path[i].trim());
			}
		}
		return result;
	}
	
	public static String getMethodName(String prefix, List<String> pathInfo) {
		StringBuilder methodName = new StringBuilder(prefix);
		if (!pathInfo.isEmpty()) {
			methodName.append(pathInfo.get(0));// first is the method name
		} else {
			methodName = new StringBuilder(); // empty it
		}
		Debug.log(LOG, "methodName = %s", methodName);
		return methodName.toString();
	}
	
	public static Map<String, String> getParams(HttpServletRequest request) {
		HashMap<String, String> result = new HashMap<String, String>();
		// only support a single parameter value for jsonrpc compatability
		Map<String, String[]> parameters = request.getParameterMap();
		for (String key : parameters.keySet()) {
			result.put(key, parameters.get(key)[0].trim());
		}
		debugParams(result);
		return result;
	}
	
	
	public static void debugParams(Map<String, String> params) {
		if (LOG.isDebugEnabled()) {
			for (String key : params.keySet()) {
				Debug.log(LOG, "param[%s] = %s", key, params.get(key));
			}
		}
	}
}
